package com.middlegroup.payadmin.controller.sys;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.github.pagehelper.PageInfo;
import com.middlegroup.common.annotation.AllLog;
import com.middlegroup.payadmin.controller.BaseController;
import com.middlegroup.payadmin.pojo.dto.DataGrid;
import com.middlegroup.payadmin.pojo.message.ApiResult;
import com.middlegroup.payadmin.pojo.po.Merchant;
import com.middlegroup.payadmin.pojo.po.Role;
import com.middlegroup.payadmin.pojo.po.RoleMerchantMap;
import com.middlegroup.payadmin.service.MenuService;
import com.middlegroup.payadmin.service.RoleMerchantMapService;
import com.middlegroup.payadmin.service.RoleService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.middlegroup.common.exception.BusinessException.notFound;


/**
 * @author pc
 */
@Controller
@RequestMapping("/sys/role")
@ApiIgnore
public class RoleController extends BaseController {

    private final RoleService roleService;
    private final MenuService menuService;
    private final RoleMerchantMapService roleMerchantMapService;

    @Resource
    private RedisTemplate redisCacheTemplate;

    @Autowired
    public RoleController(RoleService roleService, MenuService menuService, RoleMerchantMapService roleMerchantMapService) {
        this.roleService = roleService;
        this.menuService = menuService;
        this.roleMerchantMapService = roleMerchantMapService;
    }


    @GetMapping("/list")
    public String list() {
        return "sys/role/list";
    }

    @GetMapping("permissions")
    public String permissions(Integer roleId) {
        request.setAttribute("permissions", this.menuService.listPermissions());
        request.setAttribute("roleId", roleId);
        return "sys/role/permissions";
    }

    @GetMapping(value = "/edit")
    public String edit(Integer id) {
        if (id != null) {
            Role role = this.roleService.selectById(id);
            if (null == role){
                throw notFound("未找到记录");
            }
            request.setAttribute("dto", role);
        }
        return "sys/role/edit";
    }

    @GetMapping(value = "/query")
    @ResponseBody
    public PageInfo<Role> query(DataGrid grid, String name, String account) {
        EntityWrapper<Role> wrapper = new EntityWrapper<>();
        Role role = new Role();
        if (StringUtils.isNotBlank(name)){
            role.setName(name);
        }
        if (StringUtils.isNotBlank(account)){
            role.setCode(account);
        }
        wrapper.setEntity(role);
        PageHelper.startPage(grid.getPageNum(),grid.getPageSize());
        PageInfo<Role> pageInfo = new PageInfo<Role>(roleService.selectList(wrapper));
        return pageInfo;
    }

    @AllLog(module = "角色管理", methods = "保存角色", description = "添加/修改角色信息")
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<String> save(Role dto) {

        if (StringUtils.isNotBlank(dto.getSelectCodes())){
            //维护关系
            String[] selectArr = dto.getSelectCodes().split(",");
            for (String merchantCode : selectArr){
                RoleMerchantMap roleMerchantMap = new RoleMerchantMap();
                roleMerchantMap.setMerchantCode(merchantCode);
                roleMerchantMap.setRoleCode(dto.getCode());
                roleMerchantMapService.saveOrUpdate(roleMerchantMap);
            }
        }
        if (StringUtils.isNotBlank(dto.getUnselectCodes())){
            //删除关系
            String[] unArr = dto.getUnselectCodes().split(",");

            for (String merchantCode : unArr){
                EntityWrapper<RoleMerchantMap> ew = new EntityWrapper<>();
                ew.where("role_code={0} and merchant_code = {1}",dto.getCode(),merchantCode);
                roleMerchantMapService.delete(ew);
            }
        }
        //删除redis中的缓存
        Set<String> keys = redisCacheTemplate.keys("pay_admin:role_merchant_map:"+dto.getCode());
        if (CollectionUtils.isNotEmpty(keys)) {
            redisCacheTemplate.delete(keys);
        }

        if (dto.getId() != null) {
            return ApiResult.getResponse(this.roleService.updateById(dto));
        }
        return ApiResult.getResponse(this.roleService.insert(dto));
    }

    @AllLog(module = "角色管理", methods = "移除角色", description = "删除角色信息")
    @PostMapping(value = "/remove")
    @ResponseBody
    public ApiResult<String> del(Integer[] ids) {
        this.roleService.deleteRoleAndOperate(ids);
        return ApiResult.SUCCESS;
    }

    /**查询角色能管理的商户列表
     * @param code
     * @return
     */
    @RequestMapping(value = "/getRoleMerchants")
    @ResponseBody
    public List<Merchant> getRoleMerchants(@NotNull(message = "角色编码不能为空!") String code){
        return roleMerchantMapService.getRoleMerchants(code);
    }

}
